package impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import entities.LindenBet;
import entities.Lindenmovementstype;
import entities.LotteryGame;
import entities.Lindenmovement;
import entities.Userprofile;

import api.IGameEngine;
import api.IPostman;
import api.IWallet.MovementsType;

/**
 * Session Bean implementation class ILotteryProxy
 */
@Stateless(name = "ILotteryProxy")
public class LotteryProxy implements api.ILotteryProxy {

	@EJB(beanName = "IGameEngine")
	IGameEngine lotteryGame;
	@EJB(beanName = "IPostman")
	IPostman postman;

	@PersistenceContext(unitName = "PhaseBookPU")
	EntityManager em;

	@Resource
	private SessionContext context;

	private static int APP_ID_GAME = 1;
	private static int PRIZE_MULTIPLIER = 10;

	/**
	 * Default constructor.
	 */
	public LotteryProxy() {
	}

	@Override
	public boolean registerBet(int uid, int choice, int amount, int gameId) {

		Userprofile user = em.find(Userprofile.class, uid);
		if (user != null) {
			// Update account
			BigDecimal balance = user.getLindenEuros();
			user.setLindenEuros(new BigDecimal(balance.doubleValue() - amount));
			em.persist(user);

			// Add new user movement
			Lindenmovement userMovements = new Lindenmovement();
			userMovements.setUserprofile(user);
			userMovements.setLindenEuros(new BigDecimal(amount));
			userMovements.setLindenmovementstype((Lindenmovementstype) em.find(
					Lindenmovementstype.class, MovementsType.BET.ordinal()));
			userMovements.setDate(new Date());
			em.persist(userMovements);

		}

		if (lotteryGame.makeBet(APP_ID_GAME, choice, amount, uid, gameId)) {

			return true;
		} else {

			context.setRollbackOnly();
			return false;

		}
	}

	@Override
	public LotteryGame getActiveLotteryDetails() {

		return lotteryGame.getActiveLottery();
	}

	@Schedule(minute = "*/1", hour = "*", persistent = false)
	public void getLotteryDayPrizes() {

		System.out.print("*** Lottery Proxy *** getLotteryDayPrizes");
		List<LindenBet> winners = lotteryGame.getWinnerList(APP_ID_GAME);

		for (LindenBet b : winners) {

			Lindenmovement movement = new Lindenmovement();

			BigDecimal prize = new BigDecimal(b.getLindenEuros()
					* PRIZE_MULTIPLIER);

			movement.setLindenEuros(prize);

			Lindenmovementstype type = new Lindenmovementstype();
			type.setId(MovementsType.PRIZE.ordinal());

			movement.setLindenmovementstype(type);

			Userprofile user = em.find(Userprofile.class, b.getUserId());

			if (user == null)
				continue;

			movement.setUserprofile(user);

			movement.setDate(new Date());

			em.persist(movement);

			BigDecimal balance = user.getLindenEuros();

			user.setLindenEuros(new BigDecimal(balance.doubleValue()
					+ prize.doubleValue()));

			em.persist(user);

			StringBuffer buf = new StringBuffer();
			buf.append("Congratulations! You won!");
			buf.append("\n");
			buf.append("Draw Date: ");
			buf.append(b.getLotteryGame().getDrawDay().toString());
			buf.append("\n");
			buf.append("Drawn number: ");
			buf.append(b.getLotteryGame().getDrawnNumber());
			buf.append("\n");

			buf.append("Bet cost:  ");
			buf.append(b.getLindenEuros());
			buf.append("\n");
			buf.append("*** Prize *** :  ");
			buf.append(prize.doubleValue());
			buf.append(" Linden Euros\n");

			buf.append("Number of winners: ");
			buf.append(winners.size());
			buf.append("\n");

			postman.sendMail(user.getEmail(),
					"You are one of our winners this week! ", buf.toString());

		}

	}

}
